import request from '@/utils/request'

/**
 * 地区管理API - 基于oa_region表的兼容实现
 * 保持与原有/home/area接口的兼容性
 */

// 地区数据接口定义
export interface RegionItem {
  id: number
  name: string
  parent_id?: number
  level?: number
  // 兼容oa_area字段
  pid?: number
  shortname?: string
  longitude?: string
  latitude?: string
  sort?: number
  status?: number
  children?: RegionItem[]
}

// 地区管理相关接口
export const regionApi = {
  /**
   * 获取树形地区结构
   */
  getTree: (params?: { level?: number; parent_id?: number }) => {
    return request({
      url: '/api/system/region/tree',
      method: 'get',
      params,
    }) as Promise<{
      code: number
      msg: string
      data: any[]
    }>
  },

  /**
   * 获取地区列表（分页）
   */
  getList: (params?: {
    page?: number
    limit?: number
    level?: number
    parent_id?: number
    keyword?: string
    status?: number
  }) => {
    return request({
      url: '/api/system/region',
      method: 'get',
      params,
    }) as Promise<{
      code: number
      msg: string
      data: {
        list: RegionItem[]
        total: number
        page: number
        limit: number
      }
    }>
  },

  /**
   * 查看地区详情
   */
  view: (id: number) => {
    return request({
      url: `/api/system/region/${id}`,
      method: 'get',
    })
  },

  /**
   * 新增地区
   */
  add: (data: Partial<RegionItem>) => {
    return request({
      url: '/api/system/region',
      method: 'post',
      data,
    })
  },

  /**
   * 编辑地区
   */
  edit: (data: Partial<RegionItem>) => {
    return request({
      url: `/api/system/region/${data.id}`,
      method: 'put',
      data,
    })
  },

  /**
   * 删除地区
   */
  delete: (id: number) => {
    return request({
      url: `/api/system/region/${id}`,
      method: 'delete',
    })
  },

  /**
   * 获取启用地区列表（兼容/home/area/set）
   */
  getActiveList: () => {
    return request({
      url: '/api/system/region/set',
      method: 'get',
    })
  },

  /**
   * 设置地区状态
   */
  setStatus: (data: { id: number; status: number }) => {
    return request({
      url: '/api/system/region/set_status',
      method: 'post',
      data,
    })
  },
}

/**
 * 数据转换工具 - 将oa_region格式转换为oa_area格式
 */
export const regionDataConverter = {
  /**
   * 转换单个地区数据
   */
  convertToAreaFormat: (region: any): RegionItem => {
    return {
      id: region.id,
      name: region.name,
      pid: region.parent_id || 0,
      level: region.level || 1,
      shortname: region.shortname || region.name,
      longitude: region.longitude || '',
      latitude: region.latitude || '',
      sort: region.sort || 0,
      status: region.status || 1,
    }
  },

  /**
   * 转换地区列表
   */
  convertListToAreaFormat: (regions: any[]): RegionItem[] => {
    if (!Array.isArray(regions)) return []
    return regions.map(item => regionDataConverter.convertToAreaFormat(item))
  },

  /**
   * 转换树形结构
   */
  convertTreeToAreaFormat: (treeData: any[]): any[] => {
    if (!Array.isArray(treeData)) return []

    return treeData.map(item => {
      const converted = regionDataConverter.convertToAreaFormat(item)

      // 处理子节点
      if (item.children && Array.isArray(item.children)) {
        converted.children = regionDataConverter.convertTreeToAreaFormat(item.children)
      }

      return converted
    })
  },
}

/**
 * 兼容层 - 保持原有接口不变，内部使用新API
 */
export const area = {
  /**
   * 获取地区列表（兼容实现）
   */
  getList: async (params?: any) => {
    try {
      const response = await regionApi.getList(params)
      const resp = response as any
      if (resp && resp.data && resp.data.code === 0 && resp.data.data) {
        resp.data.data = regionDataConverter.convertListToAreaFormat(resp.data.data)
      }
      return resp
    } catch (error) {
      console.error('获取地区列表失败:', error)
      throw error
    }
  },

  /**
   * 查看单个地区信息
   */
  view: async (id: number) => {
    try {
      const response = await regionApi.view(id)
      const resp = response as any
      if (resp && resp.data && resp.data.code === 0 && resp.data.data) {
        resp.data.data = regionDataConverter.convertListToAreaFormat(resp.data.data)
        return resp
      }
      return resp
    } catch (error) {
      console.error('获取地区详情失败:', error)
      throw error
    }
  },

  /**
   * 新建地区
   */
  add: async (data: any) => {
    try {
      // 转换数据格式
      const convertedData = {
        name: data.name,
        parent_id: data.pid || 0,
        level: data.level || 1,
        shortname: data.shortname || data.name,
        longitude: data.longitude || '',
        latitude: data.latitude || '',
        sort: data.sort || 0,
        status: data.status || 1,
      }
      return await regionApi.add(convertedData)
    } catch (error) {
      console.error('新建地区失败:', error)
      throw error
    }
  },

  /**
   * 编辑地区
   */
  edit: async (data: any) => {
    try {
      const convertedData = {
        id: data.id,
        name: data.name,
        parent_id: data.pid || 0,
        level: data.level || 1,
        shortname: data.shortname || data.name,
        longitude: data.longitude || '',
        latitude: data.latitude || '',
        sort: data.sort || 0,
        status: data.status || 1,
      }
      return await regionApi.edit(convertedData)
    } catch (error) {
      console.error('编辑地区失败:', error)
      throw error
    }
  },

  /**
   * 删除地区
   */
  delete: async (id: number) => {
    try {
      return await regionApi.delete(id)
    } catch (error) {
      console.error('删除地区失败:', error)
      throw error
    }
  },

  /**
   * 获取启用地区列表
   */
  getActiveList: async () => {
    try {
      const response = await regionApi.getActiveList()
      const resp = response as any
      if (resp && resp.data && resp.data.code === 0 && resp.data.data) {
        resp.data.data = regionDataConverter.convertListToAreaFormat(resp.data.data)
      }
      return resp
    } catch (error) {
      console.error('获取启用地区列表失败:', error)
      throw error
    }
  },

  /**
   * 设置地区状态
   */
  setStatus: async (data: { id: number; status: number }) => {
    try {
      return await regionApi.setStatus(data)
    } catch (error) {
      console.error('设置地区状态失败:', error)
      throw error
    }
  },
}

// 向后兼容方法（保持原有导出）
export const getAreaList = area.getList
export const viewArea = area.view
export const addArea = area.add
export const editArea = area.edit
export const deleteArea = area.delete
export const getActiveAreaList = area.getActiveList
export const setAreaStatus = area.setStatus
export const saveArea = (data: any) => {
  return data.id ? editArea(data) : addArea(data)
}

export default area
